package com.czxy.test;

import com.alibaba.fastjson.JSON;
import com.czxy.domain.User;
import org.junit.Test;

import java.util.*;

public class Demo01 {

    @Test
    public  void  m01(){

        // 把对象数据 变成
        User user  = new  User("zhangsan","123");

        String s = JSON.toJSONString(user);

        System.out.println(s);


    }


    @Test
    public  void  m02(){
        //把 指定的JSON字符串 还原回对象
        String s ="{\"password\":\"123\",\"username\":\"zhangsan\"}";

        User user = JSON.parseObject(s, User.class);
        System.out.println(user);


    }




    @Test
    public  void  m03(){

        List<String> list = new ArrayList<>();

        Collections.addAll(list,"张三","李四","王五");

        String s = JSON.toJSONString(list);

        System.out.println(s);
    }


    @Test
     public  void  m04(){

      String s = "[\"张三\",\"李四\",\"王五\"]";

      List<String> list = (List<String>) JSON.parse(s);
        for (String s1 : list) {

            System.out.println(s1);

        }
    }


    @Test
    public  void  m05(){

        List<User> list = new ArrayList<>();
        list.add(new User("张三","123"));
        list.add(new User("李四","123"));
        list.add(new User("王五","123"));

        String s = JSON.toJSONString(list);
        System.out.println(s);

    }


    @Test
    public  void  m06(){

      String s = "[{\"password\":\"123\",\"username\":\"张三\"},{\"password\":\"123\",\"username\":\"李四\"},{\"password\":\"123\",\"username\":\"王五\"}]";

      List<User> users = JSON.parseArray(s,User.class);

        for (User u : users) {

            System.out.println(u.getUsername()+" "+u.getPassword());

        }
    }

    @Test
    public  void  m07(){


        Map<String,User> map = new HashMap<>();

        map.put("s01",new User("张三1","1231"));
        map.put("s02",new User("张三3","1232"));
        map.put("s03",new User("张三3","1233"));

        String s = JSON.toJSONString(map);
        System.out.println(s);














    }
    @Test
    public  void  m08(){


      String s = "{\"s02\":{\"password\":\"1232\",\"username\":\"张三3\"},\"s01\":{\"password\":\"1231\",\"username\":\"张三1\"},\"s03\":{\"password\":\"1233\",\"username\":\"张三3\"}}";

        Map<String,User> map  = JSON.parseObject(s, Map.class);

        for (String key : map.keySet()) {
          User user = JSON.parseObject(String.valueOf(map.get(key)),User.class);
            System.out.println(key+" "+user.getUsername());
        }

    }
}
